#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "task.h"

typedef void(*func_t)();

#define N 3
func_t tasks[N] = {NULL};

void LoadTask()
{
  tasks[0] = PrintLog;
  tasks[1] = DownLoad;
  tasks[2] = MysqlDataSync;
}

void HandlerTask()
{
  int i = 0;
  for(i = 0; i < N; i++)
  {
    tasks[i](); //回调函数
  }
}

void DoOtherThing()
{
  HandlerTask();
}

void ChildRun()
{
  int cnt = 5;
  //int* p = NULL;
  
  while(cnt)
  {
    printf("I am child process, pid: %d, ppid: %d, cnt: %d\n", getpid(), getppid(), cnt);
    sleep(1);
    cnt--;
    //*p = 100;
  }
}

int main()
{
  printf("I am father, pid: %d, ppid: %d\n", getpid(), getppid());
  
  pid_t id = fork();
  if(id == 0)
  {
    ChildRun();
    printf("child quit ...\n");
    exit(123);  
  }

  LoadTask();
  //father
  while(1)
  {
    int status = 0;
    // waitpid 是父进程用来回收子进程的函数
    // 第一个参数是要等待的子进程的pid，第二个参数是回收时子进程的退出状态，
    // 第三个参数是父进程应该以什么方式等待，如果是WHOHANG
    //      如果子进程没有结束，waitpid将会直接返回0
    // 返回值大于0，则等待子进程结束成功
    // 返回值小于0，则没有等到 id 对应的子进程
    pid_t rid = waitpid(id, &status, WNOHANG); //非阻塞等待
    if(rid == 0)
    {
      usleep(100000);
      printf("child is running, father check next time!\n");
      DoOtherThing();
    }
    else if(rid > 0)
    {
      if(WIFEXITED(status))
      {
        printf("child quit success! child exit code: %d\n", WEXITSTATUS(status));
      }
      else 
      {
        printf("child quit abnormal!\n");
      }
      break;
    }
    else 
    {
      printf("waitpid failed\n");
      break;
    }
  }

  //sleep(7);
  //pid_t rid = wait(NULL);
  //int status = 0;
  //pid_t rid = waitpid(id, &status, 0); 
  //if(rid > 0)
  //{
  //  if(WIFEXITED(status))
  //  {
  //    printf("child quit success! child exit code: %d\n", WEXITSTATUS(status));
  //  }
  //  else 
  //  {
  //    printf("child quit abnormal!\n");
  //  }
  //  printf("wait success, rid: %d\n", rid);
  //}
  //else
  //{
  //  printf("wait failed!\n");
  //}
  //sleep(3);
  //printf("father quit, status: %d, child quit code: %d, child quit signal: %d\n", status, (status>>8)&0xFF, status & 0x7F);
}

